<?php
/**
 * 开启服务: php7 /Users/abo_o/Dev/workplace/php/swoole2_practice/demo/server/tcp.php
 * 测试方法
 * 1.查看端口占用 netstat -an | grep 9501 => 端口被占用
 * 2.连接 telnet 127.0.0.1 9501
 *  连接成功服务端打印:Client:1 - 1 - Connect.
 *  客户端发送数据,客户端打印发送数据
 */


/**
 * 创建Server对象，监听 127.0.0.1:9501端口
 *
 * 快速起步 > 创建TCP服务器: https://wiki.swoole.com/wiki/page/476.html
 * swoole_server() 对象解析:https://wiki.swoole.com/wiki/page/14.html
 */
$serv = new swoole_server("127.0.0.1", 9501);

/**
 * 查看进程数 ps -afT | grep tcp_server.php
 */
$serv->set([
    //'reactor_num' => 2,     //reactor thread num
    'worker_num' => 4,      //worker process num cpu 1-4倍
    //'backlog' => 128,       //listen backlog
    'max_request' => 1000,
    //'dispatch_mode' => 1,
]);

/**
 * 监听连接进入事件
 * $fd 客户端连接的唯一标识
 * $reactor_id 线程标识
 *
 * 4种PHP回调函数风格: https://wiki.swoole.com/wiki/page/458.html
 */
$serv->on('connect', function ($serv, $fd, $reactor_id) {
    echo "Client:{$reactor_id} - {$fd} - Connect.\n";
});

// 监听数据接收事件
$serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
    $serv->send($fd, "Server: {$reactor_id} - {$fd}".$data);
});

// 监听连接关闭事件
$serv->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});

//启动服务器
$serv->start();